package com.cares.fw.springframework.utils;

import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;
import org.springframework.web.context.ContextLoader;

public class SpringUtils {

	/** location */
	public static final String DEFAULT_LOCATION = "classpath*:spring/beanRefContext.xml";
	/** factory key*/
	public static final String DEFAULT_FACTORY_KEY = "context";
	
	/**
	 * Returns Spring Context
	 * @return context
	 */
	public static ApplicationContext getApplicationContext() {
		// web
		ApplicationContext ac = ContextLoader.getCurrentWebApplicationContext();
		if (ac == null) {
			// batch
			BeanFactoryLocator factoryLocator = ContextSingletonBeanFactoryLocator.getInstance(DEFAULT_LOCATION);
			ac = (ApplicationContext) factoryLocator.useBeanFactory(DEFAULT_FACTORY_KEY).getFactory();
		}
		return ac;
	}
	
	/**
	 * Returns Bean instance
	 * @param clazz class
	 * @return Bean instance
	 */
	public static <T> T getBean(Class<T> clazz) {
		
		ApplicationContext ac = getApplicationContext();
		String[] bNames = ac.getBeanNamesForType(clazz);
		if (bNames == null || bNames.length == 0) {
			return null;
		} 
		
		T returnObj = null;
		Object obj = ac.getBean(bNames[0]);
        if (clazz != null && obj != null) {
        	returnObj = (T) clazz.cast(obj);
        }
        
		return returnObj;
	}
	
	public static <T> T getBean(String beanName, Class<T> clazz) {
		T returnObj = null;
		ApplicationContext ac = getApplicationContext();
		Object obj = ac.getBean(beanName);
        if (clazz != null && obj != null) {
        	returnObj = (T) clazz.cast(obj);
        }
        
		return returnObj;
	}
}
